//
//  InstituTypeChooseView.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/10/11.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "InstituTypeChooseView.h"
#import "ScreeningCell.h"
@implementation InstituTypeChooseView


-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
       [self createAndLayoutCollectionView];
    }
    return self;
}

-(void)createAndLayoutCollectionView{
    self.flowLayout = [[UICollectionViewFlowLayout alloc] init];
    self.flowLayout.itemSize = CGSizeMake(scaleLeftAndRight(75), scaleTopAndBottom(30));
    self.flowLayout.minimumLineSpacing = 10;
    self.flowLayout.minimumInteritemSpacing = 10;
    self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:self.flowLayout];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self addSubview:self.collectionView];
    self.collectionView.allowsMultipleSelection = YES;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerClass:[ScreeningCell class] forCellWithReuseIdentifier:@"ScreeningCell"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
     [self getAllChooseType];
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return [self.allDataDic allKeys].count;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSString *key = [self.allKeysArray objectAtIndex:section];
    NSArray *valuesArra = self.allDataDic[key];
    return valuesArra.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ScreeningCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ScreeningCell" forIndexPath:indexPath];
    NSString *key = [self.allKeysArray objectAtIndex:indexPath.section];
    NSArray *values = self.allDataDic[key];
    cell.label.text = values[indexPath.row];
    cell.label.font = [UIFont systemFontOfSize:13];
    return cell;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(0, 15, 0, 15);
}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqual:UICollectionElementKindSectionHeader]) {
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header" forIndexPath:indexPath];
        for (UIView *views in view.subviews) {
            [views removeFromSuperview];
        }
        [self createTittleLabel:view WithTitle:[self.allKeysArray objectAtIndex:indexPath.section]];
        self.label.tag = 1000 + indexPath.section;
        return view;
    }else{
        UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
        for (UIView *views in view.subviews) {
            [views removeFromSuperview];
        }
        UIView *lineView = [[UIView alloc] init];
        lineView.backgroundColor = [UIColor lightGrayColor];
        [view addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(view.mas_left).offset(15);
            make.right.equalTo(view.mas_right).offset(-15);
            make.height.mas_equalTo(0.5);
            make.centerY.equalTo(view.mas_centerY);
        }];
        if (indexPath.section == self.allKeysArray.count - 1) {
            self.sureBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [view addSubview:self.sureBtn];
            [self.sureBtn setTitle:@"确定" forState:UIControlStateNormal];
            [self.sureBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            self.sureBtn.backgroundColor = [UIColor orangeColor];
            [self.sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(view.mas_centerX);
                make.top.equalTo(lineView.mas_bottom).offset(scaleTopAndBottom(5));
                make.size.mas_equalTo(CGSizeMake(scaleLeftAndRight(75), scaleTopAndBottom(30)));
            }];
            self.sureBtn.layer.cornerRadius = 4;
            self.sureBtn.layer.masksToBounds = YES;
            [self.sureBtn addTarget:self action:@selector(showAlldata) forControlEvents:UIControlEventTouchUpInside];
        }
        return view;
    }
    
}
-(void)showAlldata{
    
    [self removeFromSuperview];
    if (self.closeViewBlock) {
         self.closeViewBlock();
    }
    if (self.valuesStrBlock) {
        NSMutableString *str = [[NSMutableString alloc] init];
        for (NSInteger i = 0; i < self.dataValuesArray.count; i++) {
            [str appendString:[NSString stringWithFormat:@" %@",self.dataValuesArray[i]]];
        }
        self.valuesStrBlock(str);
    }

}
-(void)createTittleLabel:(UICollectionReusableView *)view WithTitle:(NSString *)title{

    self.label = [[UILabel alloc] init];
    _label.textAlignment = NSTextAlignmentCenter;
//    _label.adjustsFontSizeToFitWidth = YES;
    _label.text = title;
    _label.font = [UIFont systemFontOfSize:15];
    _label.layer.borderWidth = 1.0f;
    _label.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _label.textColor = [UIColor blackColor];
    [view addSubview:_label];
    [_label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view.mas_left).offset(15);
        make.width.mas_equalTo(scaleLeftAndRight(75));
        make.top.equalTo(view.mas_top).offset(10);
        make.bottom.equalTo(view.mas_bottom).offset(-10);
    }];
    _label.layer.cornerRadius = 4;
    _label.layer.masksToBounds = YES;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    if (section == self.allKeysArray.count - 1) {
        return CGSizeMake(WIDTH - 30, scaleTopAndBottom(100));
    }
    return CGSizeMake(WIDTH - 30, scaleTopAndBottom(15));
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    //    return CGSizeMake(WIDTH, scaleTopAndBottom(30));
    return CGSizeMake(scaleLeftAndRight(75) + 15, scaleTopAndBottom(30) + 20);
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    if (self.chooseDataArray.count >= 3) {
//        UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:@"提示" message:@"机构类型最多可以选择3个" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//        [alertVeiw show];
//        return;
//    }
    NSString *chooseTitle = [self.allKeysArray objectAtIndex:indexPath.section];
    NSArray *valusArray = self.allDataDic[chooseTitle];
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[valusArray objectAtIndex:indexPath.row],chooseTitle, nil];
    [self.chooseDataArray addObject:dict];
    NSLog(@"选取到的key%@",chooseTitle);
    NSLog(@"选取到的值%@",[valusArray objectAtIndex:indexPath.row]);
    [self.dataValuesArray addObject:[valusArray objectAtIndex:indexPath.row]];
//    NSLog(@"你选了:%@",label.text);
    ScreeningCell *cell = (ScreeningCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.label.layer.borderColor = [UIColor orangeColor].CGColor;
    cell.label.textColor = [UIColor orangeColor];
//    NSLog(@"选取的数组%@",self.chooseDataArray);
}
-(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *chooseTitle = [self.allKeysArray objectAtIndex:indexPath.section];
    NSArray *valusArray = self.allDataDic[chooseTitle];
//    for (NSDictionary *dic in self.chooseDataArray) {
//        for (NSInteger i = 0; i < valusArray.count; i++) {
//            if ([dic[chooseTitle] isEqual:valusArray[i]]) {
//                [self.chooseDataArray removeObject:dic];
//            }
//        }
//    }
//    [self.chooseDataArray removeObject:[valusArray objectAtIndex:indexPath.row]];
    for (NSInteger i = 0; i < self.chooseDataArray.count; i++) {
        NSDictionary *dic = self.chooseDataArray[i];
        if ([[dic allValues][0] isEqual:[valusArray objectAtIndex:indexPath.row]]) {
            [self.chooseDataArray removeObject:dic];
        }
    }
    NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[valusArray objectAtIndex:indexPath.row],chooseTitle, nil];
    for (NSInteger i = 0; i < self.dataValuesArray.count; i++) {
        if ([self.dataValuesArray[i] isEqual:[valusArray objectAtIndex:indexPath.row]]) {
            [self.dataValuesArray removeObject:self.dataValuesArray[i]];
        }
    }
//    for (NSDictionary *dic in self.chooseDataArray) {
//        NSLog(@"这是他么的字典数值%@",dic);
//        if ([[dic allValues][0] isEqual:[valusArray objectAtIndex:indexPath.row]]) {
//            [self.chooseDataArray removeObject:dic];
//        }
//    }
    NSLog(@"数组%@",self.chooseDataArray);
    ScreeningCell *cell = (ScreeningCell *)[collectionView cellForItemAtIndexPath:indexPath];
    cell.label.layer.borderColor = [UIColor lightGrayColor].CGColor;
    cell.label.textColor = [UIColor blackColor];
    
}

-(void)createLineView:(UICollectionReusableView *)view{

}
#pragma mark -数据懒加载
-(NSDictionary *)dataDic{
    if (_dataDic == nil) {
        _dataDic = @{@"音乐":@[@"乐器",@"声乐"],@"绘画":@[@"儿童画",@"国画",@"沙画"],@"舞蹈":@[@"民族舞",@"国际舞",@"现代舞",@"芭蕾舞"],@"科技":@[@"机器人",@"乐高"],@"手工":@[@"黏土",@"折纸",@"烘焙",@"木工"],@"国学":@[@"书法",@"棋类",@"古文"],@"英语":@[@"线上英语",@"线下英语"],@"体育":@[@"篮球",@"羽毛球",@"乒乓球",@"跆拳道",@"橄榄球",@"剑道",@"武术"],@"教育":@[@"语文",@"数学",@"物理",@"化学",@"奥数",@"实验"],@"早教":@[]};
    }
    return _dataDic;
}
-(NSArray *)keysArray{
    if (_keysArray == nil) {
        _keysArray = @[@"音乐",@"绘画",@"舞蹈",@"科技",@"手工",@"国学",@"英语",@"体育",@"教育",@"早教"];
    }
    return _keysArray;
}
-(NSMutableArray *)allKeysArray{
    if (_allKeysArray == nil) {
        _allKeysArray = [[NSMutableArray alloc] init];
    }
    return _allKeysArray;
}
-(NSMutableDictionary *)allDataDic{
    if (_allDataDic == nil) {
        _allDataDic = [[NSMutableDictionary alloc] init];
    }
    return _allDataDic;
}
-(void)getAllChooseType{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServerIp@"/institutionApp/categoryListAll";
    NSDictionary *parma = [NSDictionary dictionaryWithObjectsAndKeys:@"true",@"needChildren", nil];
    [manager POST:url parameters:parma progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSArray *array = jsonDic[@"list"];
        for (NSDictionary *dict in array) {
            NSDictionary *chidrensArra = dict[@"childrens"];
            NSMutableArray *valusArra = [[NSMutableArray alloc] init];
            for (NSDictionary *chilredDic in chidrensArra) {
                NSString *titles = chilredDic[@"name"];
                NSString *ids = chilredDic[@"id"];
                NSDictionary *dicss = [NSDictionary dictionaryWithObjectsAndKeys:titles,ids, nil];
                [self.vlauesAndIdsArray addObject:dicss];
                [valusArra addObject:titles];
            }
            [self.allDataDic setObject:valusArra forKey:dict[@"name"]];
            [self.allKeysArray addObject:dict[@"name"]];
        }
        [self.collectionView reloadData];
        NSLog(@"获取到的崭新的选项%@",self.dataDic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
-(NSMutableArray *)chooseDataArray{
    if (_chooseDataArray == nil) {
        _chooseDataArray = [[NSMutableArray alloc] init];
    }
    return _chooseDataArray;
}

-(NSMutableDictionary *)chooseDataDic{
    if (_chooseDataDic == nil) {
        _chooseDataDic = [[NSMutableDictionary alloc] init];
    }
    return _chooseDataDic;
}
-(NSMutableArray *)chooseIdsArray{
    if (_chooseIdsArray == nil) {
        _chooseIdsArray = [[NSMutableArray alloc] init];
    }
    return _chooseIdsArray;
}
-(NSMutableArray *)vlauesAndIdsArray{
    if (_vlauesAndIdsArray == nil) {
        _vlauesAndIdsArray = [[NSMutableArray alloc] init];
    }
    return _vlauesAndIdsArray;
}
-(NSMutableArray *)dataValuesArray{
    if (_dataValuesArray == nil) {
        _dataValuesArray = [[NSMutableArray alloc] init];
    }
    return _dataValuesArray;
}
@end
